import os
from utils.Logger import LogPrint
from enum import Enum
from PIL import Image
from datetime import datetime
from PyQt6.QtWidgets import QMessageBox
from PyQt6.QtCore import QRunnable,QThread, QObject,QTimer,pyqtSignal
from views.WaitPromptBox import WaitPromptBox
from utils.PdfUtils import pdfConvertToPreImage,ImageFmt


isThreadRunning= False

class MyThread(QThread):
    signal = pyqtSignal(list)

    def __init__(self,data=None):
        super().__init__()
        self.data=data

    def run(self):
        global isThreadRunning
        isThreadRunning=True
        pdfPath=self.data[0]
        # imageSavePath=self.data[2]
        # pageNoList=self.data[3]
        # paramQualit=self.data[4]
        # paramFmt=self.data[5]
        # pageStartEndList=self.data[6]
        LogPrint.debug('run data',self.data)
        
        images,localImgPath=pdfConvertToPreImage(pdfPath)
        isThreadRunning= False
        result=[]
        result.append(images)
        result.append(localImgPath)
        self.signal.emit(result)
        self.quit()



class PdfConvertTask(QObject):


    def __init__(self,parent=None):
        super().__init__()
        self.data=[]
        self.waitBox=None
        self.callback=None
        self.parent=parent
        self.thread=None

    #在子进程中执行加载pdf过程
    def startPdfConvertTask(self,pdfPath,quality=0,savePath=None,fmt=ImageFmt.JPG,
                            export=False,startPage=1,endPage=None,callback=None):
        
        LogPrint.info('pdfPath ',pdfPath,quality,savePath,fmt)

        self.callback=callback

        self.data=[]
        self.data.append(pdfPath)
        self.data.append(quality)
            
        self.thread = MyThread(self.data)
        self.thread.signal.connect(self.threadFinish)
        self.thread.start()

        self.startWaitPromptBox()

    #定时启动显示等待框
    def startWaitPromptBox(self):
        

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.showWaitPromptBox)
        self.timer.start(1000)  # 每秒更新一次

    def showWaitPromptBox(self):
        if isThreadRunning:
            self.waitBox=WaitPromptBox(self.parent,'正在加载文件')
            self.waitBox.show()
        self.timer.stop()
    #线程停止
    def threadFinish(self,result):
        if self.waitBox and self.waitBox.isVisible():
            self.waitBox.close()
        images=result[0]
        localImgPath=result[1]
        if images or localImgPath:
            #QMessageBox.information(self.parent,'系统提示','导出完成')
            if self.callback:
                self.callback(images,localImgPath)

        self.unInit()

    def unInit(self):
        if self.thread:
            self.thread.wait()
            del self.thread